var BSTMG = BSTMG || {};
BSTMG.common = {
    init: function() {
        var that = this;
        /* 显示当前页菜单 */
        that.showCurrentMenu();
        /* 绑定修改密码功能 */
        that.modifyPassword();
    },
    modifyPassword: function(){
    	BSTYUN.dialog.modifypsd = function(){
    		var dialog = null;
    		var html = '<div id="modifypsdbox">';
    		html += '<div class="input-group"><span class="input-group-addon">旧密码</span><input type="password" name="oldPwd" class="form-control" placeholder="旧密码"></div>';
    		html += '<div class="input-group"><span class="input-group-addon">新密码</span><input type="password" name="newPwd" class="form-control" placeholder="新密码"></div>';
    		html += '<div class="input-group"><span class="input-group-addon">确认密码</span><input type="password" name="confirmPwd" class="form-control" placeholder="确认密码"></div>';
    		html += '</div>';
    		dialog = BSTYUN.dialog.creat({
    			id : "modify",
    			content : html,
    			title: '修改密码',
    			init: function(){
    				var $box = $(this['DOM']['border'][0]);
    				//初始化，绑定验证事件
    				$box.find("input[name=oldPwd]").on("blur",checkOldPwd);
    				$box.find("input[name=newPwd]").on("blur",checkNewPwd);
    				$box.find("input[name=confirmPwd]").on("blur",checkConfirmPwd);
    			}
    		});
    		dialog.button({
    			name : "确定",
    			focus : true,
    			callback : function(){
    				return updatePwd();
    			}
    		});
    		dialog.button({
    			name : "取消",
    			callback : function(){}
    		});
    		//校验密码非空
    		function checkOldPwdNull(){
    			var oldPwd = $('input[name=oldPwd]').val();
				oldPwd = $.trim(oldPwd);
				if(oldPwd.length <1){
					BSTYUN.dialog.warn('请输入旧密码！');
					return false;
				}else{
					return true;
				}
    		}
    		//校验密码
    		function checkOldPwd(){
    			if(checkOldPwdNull())
    				var oldPwd = $('input[name=oldPwd]').val();
					oldPwd = $.trim(oldPwd);
					$.ajax({
	        			url: '/loginAdmin/operate/checkPwd',
	        			type: 'post',
	        			dataType: 'json',
	        			data: {oldPwd:oldPwd},
	        			success: function(data){
	        				if(data.isOk == false){
	        					BSTYUN.dialog.warn('密码输入错误！请重新输入！');
	        					return false;
	        				}else{
	        					return true;
	        				}
	        			}
					})
    		};
    		//校验新密码 
    		function checkNewPwd(){
    			var newPwd = $('input[name=newPwd]').val();
				newPwd = $.trim(newPwd);
				if(newPwd.length > 0 && (newPwd.length < 8 || newPwd.length > 16)){
					BSTYUN.dialog.warn('密码长度为8-16位！请重新输入！');
					return false;
				}else if(newPwd.length < 1){
					BSTYUN.dialog.warn('请输入新密码！');
					return false;
				}
				return true;
    		}
    		//校验两次密码是否一致
    		function checkConfirmPwd(){
    			if(checkNewPwd()){
    				var confirmPwd = $('input[name=confirmPwd]').val();
					confirmPwd = $.trim(confirmPwd);
					var newPwd = $('input[name=newPwd]').val();
					newPwd = $.trim(newPwd);
					if(confirmPwd.length > 0 && confirmPwd != newPwd){
						BSTYUN.dialog.warn('两次输入密码不一致！');
						return false;
					}else if(confirmPwd.length < 1){
						BSTYUN.dialog.warn('请输入确认密码！');
						return false;
					}else{
						return true;
					}
					
    			}else{
    				return false;
    			}
    		}
    		//提交修改密码
    		function updatePwd(){
    			if(checkOldPwdNull() && checkNewPwd() && checkConfirmPwd()){
    				var flag = true;
    				var oldPwd = $.trim($('input[name=oldPwd]').val());
    				var newPwd = $.trim($('input[name=newPwd]').val());
					$.ajax({
	        			url: '/loginAdmin/operate/updatePwd',
	        			type: 'post',
	        			async : false,
	        			dataType: 'json',
	        			data: {
	        				newPwd:newPwd,
	        				oldPwd:oldPwd
	        			},
	        			success: function(data){
	        				if(data.isOk == true && data.isRight == true){
	        					BSTYUN.dialog.ok('密码修改成功！');
	        				}else if(data.isRight == false){
	        					BSTYUN.dialog.warn('原始密码填写错误！请重新填写！');
	        					flag = false;
	        				}else {
	        					flag = false;
	        				}
	        			}
					})
    				return flag;
    			}else{
    				BSTYUN.dialog.warn('请输入相关信息！');
    				return false;
    			}
    		}
    	}
    	var $modify = $("#modifypassword");
    	$modify.on("click",function(){
    		BSTYUN.dialog.modifypsd();
    	});
    },
    //菜单打开功能增加，打开当前页的菜单
    showCurrentMenu: function() {
        var $menu = $(".sidebar-menu > .treeview > a");
        if (typeof(currentMenu) !== "undefined") {
            var currentmenu = $.trim(currentMenu);
            $menu.each(function() {
                var $this = $(this);
                if ($this.hasClass(currentmenu)) {
                    //$this.trigger('click');
                    $this.next('.treeview-menu').show();
                    $this.parent('.treeview').data('isActive', true).addClass("active");
                    $this.children(".fa-angle-left").first().removeClass("fa-angle-left").addClass("fa-angle-down");
                }
            });
        } else {
            if (window.console) {
                console.warn('左侧菜单打开页必须定义变量');
            }
        }
    },
    //分页功能。
    hjhPages: function(url,args,callback) {
    	var prepareHTML = '<div class="row"><div class="col-xs-4"><div class="dataTables_info"id="pageInfor">当前显示数据<select class="input-sm showCountAstrict"><option value="10">10</option><option value="20">20</option><option value="30">30</option><option value="40">40</option><option value="50">50</option></select>条，共<b class="allCount">0</b>条</div></div><div class="col-xs-8"><div class="dataTables_paginate paging_bootstrap text-right"><ul class="pagination"><li><a href="#"data-goto="1">1</a></li></ul></div></div></div>',
			$pagebox = $("#pagesbox");
    	if($pagebox.length == 0){
    		var warn = "分页程序必须要有盒子包含分页按钮,请在页面中放置一个id为pagesbox的块级元素";
    		if(window.console){console.warn(warn);}else{alert(warn);}
    		return false;
    	}
    	if($.isFunction(args)){
    		callback = args;
    		args={};
    	}
        //添加到文档中
    	$pagebox.html(prepareHTML);
        var that = this,
            $pageinfor = $pagebox.find("#pageInfor"),
            $astrict = $pageinfor.find(".showCountAstrict"),
            $all = $pageinfor.find(".allCount"),
            $pagebutton = $pagebox.find(".pagination"),
            $dataTable = $(".dataTable");
        var last = $.trim($astrict.val()),
            all = $.trim($all.text()),
            pagecount = Math.ceil(all / last);
        $pagebutton.on('click', 'li a', function() {
            var $this = $(this),
                go = $.trim($this.attr("data-goto")), //点击的位置
                current = 0; //当前的位置
            last = $.trim($astrict.val()); //一次获取的数据量
            pagecount = Math.ceil($.trim($all.text()) / $.trim($astrict.val())); //获取分页总数
            //防止重复提交
            var isActive = $this.parent('li').hasClass('active');
            if (isActive) {
                return false;
            }

            $pagebutton.children('li').each(function() {
                var $this = $(this);
                if ($this.hasClass('active')) {
                    current = parseInt($this.children('a').attr("data-goto"));
                }
            });
            if (go == 'prev' || go == 'next') {
                go = go == 'prev' ? --current : ++current;
                switch (go) {
	                case -1:
	                    BSTYUN.dialog.warn('当前已是第一页！');
	                    return false;
	                    break;
                    case 0:
                        BSTYUN.dialog.warn('当前已是第一页！');
                        return false;
                        break;
                    case pagecount + 1:
                        BSTYUN.dialog.warn('当前已是最后一页！');
                        return false;
                        break;
                }
            };
            go = parseInt(go);
            var params = $.extend({},{page: go,last: last},args);
            $.ajax({
                url: url,
                type: 'post',
                dataType: 'json',
                data: params,
                beforeSend: function(){
                	var html = '<div id="loading_data" style="text-align:center;position:absolute"><img src="/images/admin/loading_data.gif" /></div>';
                	var width = $dataTable.width()/2 -20,
                		height = $dataTable.height()/2 -20;
                	if( $dataTable.height() < 40){
                		height = 65;
                	}
                	$dataTable.parent().css("position","relative").append($(html).css({"top":height,"left":width}));
                },
                complete: function(){
                	$dataTable.parent().find("#loading_data").remove();
                },
                success: function(data) {
                	callback && callback(data);
                	$all.text(data.totalRows);					//更新数据总量
                    adjustPageButton(go, last, data.totalRows);	//调整下面的按钮
                },
                error: function(event) {
                    BSTYUN.dialog.warn('网络异常，请稍后尝试');
                }
            });
            return false;
        });
        $astrict.on('change', function() {
            var $this = $(this),
                last = parseInt($this.val()),
                totalRows = parseInt($all.val());
            adjustPageButton(1,$.trim($astrict.val()),$.trim($all.text()));
            $pagebutton.children('li').eq(1).removeClass('active').children('a').trigger('click');
        });
        
        //默认显示第一页,html代码必须有第一页的a标签。
        $pagebutton.find('li a').trigger('click');
        
        function adjustPageButton(current,last,all){
    		var $buttons = $pagebutton,
    			pagecount = Math.ceil(all/last),
    			html = '<li class="prev"><a href="#" data-goto="prev">← 上一页</a></li>',
    			temple = '',
    			isten = 0;
    			if(current < 11){
    				for(var i = 1; i <= current + Math.abs(11 - current); i++){
    					if(i > pagecount){break;}
    					if(current == 1 && i == 1){
    						html = '<li class="prev disabled"><a href="#" data-goto="prev">← 上一页</a></li>';
    					}
    					i == current ?
    					html += '<li class="active"><a href="#" data-goto="'+i+'">'+i+'</a></li>' :
    					html += '<li><a href="#" data-goto="'+i+'">'+i+'</a></li>';
    				}
    			}else{
    				var diff = Math.abs(pagecount - current);
    				if(diff < 8){
    					for(var i = current - (8 - diff); i < (current+8); i++){
    						if(i > pagecount){break;}
    						i == current ?
    						html += '<li class="active"><a href="#" data-goto="'+i+'">'+i+'</a></li>' :
    						html += '<li><a href="#" data-goto="'+i+'">'+i+'</a></li>';
    					}
    				}else{
    					for(var i = current - 2; i < (current+8); i++){
    						if(i > pagecount){break;}
    						i == current ?
    						html += '<li class="active"><a href="#" data-goto="'+i+'">'+i+'</a></li>' :
    						html += '<li><a href="#" data-goto="'+i+'">'+i+'</a></li>';
    					}
    				}
    			}
    		current == pagecount ? 
    		html += '<li class="next disabled"><a href="#" data-goto="next">下一页 → </a></li>'	:
    		html += '<li class="next"><a href="#" data-goto="next">下一页 → </a></li>';
    		$buttons.empty().html(html);
    	}
    },
    //二级菜单
    hjhMenu: function(){
    	$.fn.extend({
			dynaMenu: function(data){
				var $doc = $(document),
					$window = $(window);
				$.each(this,function(index,val){
					var $this = $(this);	//val 和 this 相同;
					// 添加菜单项
					var $box = $('<ul class="dynadown-menu" role="menu"></ul>');
					$.each(data,function(index,val){
						var tem = '<li role="presentation"><a role="menuitem" tabindex="-1" href="#" data-boundtype="'+val.boundtype+'">'+val.itemname+'<span class="fa fa-chevron-right"></span></a></li>';
						$tem = $(tem);
						$tem.on("click",val.clickcallback).on("mouseenter",function(){
							var data = val.hover;
							hoverAction.call(this,data.url,data.callback);
						}).appendTo($box);
					});
					$this.append($box);
					
					$this.on("click",".btn",function(event){
						var $this = $(this),
							$parent = $this.parent();
						//关闭其他下拉菜单
						$(".dynadown-menu").hide();
						
						if($parent.hasClass("open")){
							$box.hide();
							$parent.removeClass("open");
						}else{
							$box.show();
							$parent.addClass("open");
						}
						return false;
					});
				}); //end each;
				
				//绑定文档事件，关闭打开的下来菜单
				$doc.on("click",function(event){
					var $tar = $(event.target),
						$parent = $tar.parents(".dynadown");
					if(!!$parent.length){
						return false;
					}
					closeMenu.call($doc.find(".dynadown"));
				});
				
				//请求二级菜单的数据
				function hoverAction(url,callback){
					 var $rootli = $(this);	//li标签
		        	 $rootli.parent().find(".subitembox").hide();	//隐藏其他标签
		        	 
		        	 var $subitembox = $rootli.find(".subitembox");
		        	 $subitembox.show();
		        	 
		        	 var isExistData = $subitembox.find(".sub-item").length;
	        		 if(!!isExistData){return false;}
	        		 
	        		 var params = {};
	        		 $.ajax({
	        			url: url,
	        			type: 'post',
	        			dataType: 'json',
	        			data: params,
	        			beforeSend: function(){
	        				var $box = $('<div class="subitembox"><img class="loading" src="/images/user/loading_blue.gif"/></div>');
		        			$box.css({"left":"-130px","top":"-10px"});
		        			$rootli.append($box);
	        			},
	        			complete: function(){
	        				$rootli.find(".loading").remove();
	        			},
	        			success: function(data){
	    					var $box = $('<ul class="sub-item" role="menu"></ul>'),
	    						$searchbox = $('<li class="searchbar"><div class="input-group"><input type="text" class="form-control"><span class="glyphicon glyphicon-search"></span></div></li>'),
	    						$scrollbox = $('<li class="scrollbox"></li>'),
	    					    $content = $("<ul class='scrollcontent'></ul>");
	    					var newdata = callback(data);
	    					$.each(newdata.items,function(index,val){
	    						var tem = '<li role="presentation"><a role="menuitem" tabindex="-1" href="#" data-id="'+val.id+'">'+val.name+'</a></li>';
	    						$tem = $(tem);
	    						$tem.appendTo($content);
	    					});
	    					$scrollbox.append($content);

	    					$box.append($searchbox);
	    					$box.append($scrollbox);
	    					/* 计算宽度 */
	    					var maxwidth = 0;
	    					$rootli.find(".subitembox").append($box.show()).find(".scrollcontent li").each(function(){
	    						var scw = $(this)[0].scrollWidth;
	    						if(scw > maxwidth){
	    							maxwidth = scw;
	    						}
	    					});
	    					maxwidth += 30;
	    					if(maxwidth < 130){ maxwidth = 130}
	    					
	    					//调整二级菜单的高度
	    					var width = $box.width(),
	    						height = $box.height();
	    					var cltwidth = $window.width(),
	    						cltheight = $window.height(),
	    						scrolltop = $doc.scrollTop(),
	    						rootop = $rootli.offset().top;
	    					var nowt = -50,
	    						nowl = -maxwidth;
	    					
	    					if((cltheight + scrolltop) < (height + rootop)){
	    						nowt = (cltheight + scrolltop) - (height + rootop) - 0;
	    					}
	    					
	    					//console.log("cltheight"+cltheight+"height:"+height+";rootop:"+rootop+";nowt:"+nowt);
	    					$rootli.find(".subitembox").css({
	    						"width": maxwidth,
	    						"left": nowl,
	    						"top": nowt
	    					});
	    					//搜索事件
	    					$searchbox.on("click",".glyphicon",function(){
	    						searchKeyWord.call($(this).prev());
	    					}).on("keydown",".form-control",function(event){
	    						if(event.which == 13){
	    							$(this).next().trigger("click");
	    						}
	    					});
	    					//绑定点击事件
	    					$scrollbox.on("click","a",function(){
	    						var $this = $(this),
	    							id = $.trim($this.attr("data-id")),
	    							txt = $.trim($this.text()),
	    							boundtype = $.trim($this.parents(".subitembox").prev().attr("data-boundtype"));
	    						$rootli.parents(".dynadown-menu").prev().html(txt+'<span class="caret"></span>').attr("data-id",id).attr("data-value",txt).attr("data-boundtype",boundtype);
	    						closeMenu.call($rootli.parents(".dynadown"));
	    						return false;
	    					});
	    					//var nicesx = $scrollbox.niceScroll(); 滚动条插件
	        			},
	        			error: function(){
	        				$rootli.find(".subitembox").html("<span style='color:#f00;font-size:12px;'>查无数据！</span>");
	        				BSTYUN.dialog.warn('网络异常，请稍后尝试');
	        			}
		        	 });//end ajax
		        	 
				};//end function hoverAction
				//搜索功能
				function searchKeyWord(){
					var $this = this,
						$parent = $this.parents(".searchbar"),
						$subitembox = $parent.parents(".subitembox"),
						boundtype = $subitembox.prev().attr("data-boundtype"),
						$scrollbox = $parent.next(),
						$ul = $scrollbox.children(".scrollcontent"),
						$list = $ul.children("li"),
						value = $.trim($this.val());
					switch (boundtype){
						case '1':
							$.ajax({
				                url: '/sysAdmin/voucher/cListSearch',
				                type: 'post',
				                dataType: 'json',
				                data: {value:value},
				                success: function(data) {
				                	var subhtml = '';
				                	$.each(data.items,function(index,val){
				                		var useremail = val.userEmail,
				                			usertel = val.userTel,
				                			id = val.userId;
				                		var text = (useremail == null || useremail == '') ? usertel : useremail;
				                		
				                		subhtml += '<li role="presentation"><a href="#" data-id="'+id+'">'+text+'</a></li>';
				                		
				                	});
				                	$ul.html(subhtml);
				                },
				                error: function(event) {
				                    BSTYUN.dialog.warn('网络异常，请稍后尝试');
				                }
				            });
							break;
						case '2':
							$.ajax({
				                url: '/sysAdmin/voucher/uListSearch',
				                type: 'post',
				                dataType: 'json',
				                data: {value:value},
				                success: function(data) {
				                	var subhtml = '';
				                	$.each(data.items,function(index,val){
				                		var useremail = val.userEmail,
				                			usertel = val.userTel,
				                			id = val.userId;
				                		var text = (useremail == null || useremail == '')? usertel : useremail;
				                		
				                		subhtml += '<li role="presentation"><a href="#" data-id="'+id+'">'+text+'</a></li>';
				                		
				                	});
				                	$ul.html(subhtml);
				                },
				                error: function(event) {
				                    BSTYUN.dialog.warn('网络异常，请稍后尝试');
				                }
				            });
							break;
						case '3':
							$.ajax({
				                url: '/sysAdmin/voucher/mpListSearch',
				                type: 'post',
				                dataType: 'json',
				                data: {value:value},
				                success: function(data) {
				                	var subhtml = '';
				                	$.each(data.items.productList,function(index,val){
				                		var productname = val.productName,
				                			productversion = val.productVersion;
				                		subhtml += '<li role="presentation"><a href="#" data-id="'+productversion+'">'+productname+'</a></li>';
				                	});
				                	$.each(data.items.mealList,function(index,val){
				                		var mealname = val.mealName,
			                				mealversion = val.mealVersion;
				                		subhtml += '<li role="presentation"><a href="#" data-id="'+mealversion+'">'+mealname+'</a></li>';
				                	});
				                	$ul.html(subhtml);
				                },
				                error: function(event) {
				                    BSTYUN.dialog.warn('网络异常，请稍后尝试');
				                }
				            });
							break;
					}
					var temple = [];
					$list.each(function(){
						var $this = $(this),
							txt = $.trim($this.find("a").text());
						if(txt.indexOf(value) >= 0){
							temple.push($this.detach());
						}
					});
					$.each(temple.reverse(),function(index,val){
						val.prependTo($ul);
					});
				};
				//关闭当前下拉菜单
				function closeMenu(){
					var $this = $(this);
					var $dymenu = $this.find(".dynadown-menu"),
						$submenu = $this.find(".subitembox");
					$dymenu.hide();
					$submenu.hide();
					$this.removeClass("open");
				};
				return this;
			}//end extend 
		});
    }
};
BSTMG.plugins = {
	/* 右键菜单插件 */
	kittyMenu: function(){
		$.fn.extend({
			kittyMenu: function(menu){
				var $doc = $(document),
					$widnow = $(window),
					$body = $("body");
				this.each(function(){
					var $this = $(this);
					$this.css({"position":"relative"});
					var rootpageX = $this.offset().left,
						rootpageY = $this.offset().top;

					var $preHTML = $('<div class="kittyMenu"><div class="btn-group-vertical"></div></div>'),
						$prbox = $preHTML.children("div");
					$preHTML.css({"position":"absolute","display":"none","zIndex":"100"}).appendTo($this);
					$doc.on("click",function(event){
						var $this = $(event.target);
						if($this.parents(".kittyMenu").length){
						}else{
							$preHTML.hide();
						}
					});
					$this.on("contextmenu",function(event){
						var pageX = event.pageX,
							pageY = event.pageY,
							cltwidth = $widnow.width(),
							cltheight = $widnow.height(),
							origevent = event;
						//添加菜单
						$prbox.empty();
						$.each(menu,function(index,val){
							var $tmple = $('<button type="button" class="btn '+val.className+'">'+val.menuname+'</button>');
							$tmple.on("click",function(){
								val.clickaction && val.clickaction(origevent);
								$preHTML.hide();
								return false;
							});
							$prbox.append($tmple);
						});
						/* 调整下拉菜单位置 */
						var width = $preHTML.width(),
							height = $preHTML.height();
						var nowx = pageX - rootpageX,
							nowy = pageY - rootpageY;
						//console.log("cltwidth:"+cltwidth+";pageX"+pageX+";差："+(cltwidth - pageX))
						if( (cltwidth - pageX) < width ){
							nowx = pageX - rootpageX - width;
						}
						if( (cltheight - pageY) < height ){
							nowy = pageY - rootpageY - height;
						}
						
						$preHTML.css({left:nowx,top:nowy}).show();
						
						return false;
					});
				});
				return this;
			}
		});
	},
	/* 加载动画插件 */
	initkittyLoading: function(){
		$.extend({
			kittyLoading: function(){
				var defaults = { id : 1 , url : "/images/admin/loading_normal.gif" , zIndex : 99 , coordinate : { x: 10, y : 10 , w : 100 , h : 100} },
					stack = {},
					$window = $(window),
					$doc = $(document);
				function loading(setttings){
					$.extend(defaults,setttings);
					this.defaults = defaults;
					this.init();
					return this;
				};
				loading.prototype = {
					init: function(){
						var html = "<div class='kittyloading'></div>",
							$loading = $(html);
						var coordinate = this.defaults.coordinate;
						$loading.css({
							"position": "absolute" ,
							"top" : coordinate.y ,
							"left" : coordinate.x ,
							"width" : coordinate.w ,
							"height" : coordinate.h ,
							"z-index" : this.defaults.zIndex ,
							"background": "url("+this.defaults.url+") rgba(255,255,255,0.5) no-repeat center 40%"
						});
						$doc.find("body").append($loading);
						
						if(stack[this.defaults.id]){
							this.defaults.id++;	
						}
						stack[this.defaults.id] = $loading;
					},
					destory: function(id){
						if(id){
							stack[id].remove();
							return true;
						}
						for(var key in stack) {
							stack[key].remove();
						}
					}
				};
				function getWindowProty(){
					return {
						clientx: $window.width(),
						clienth: $window.height(),
						scrolltop: $doc.scrollTop(),
						scrolltop: $doc.scrollLeft(),
					}
				};
				return loading;
				
				
			}
		});
	},
	/* 选项卡插件 */
	prettyTab: function(){
		$.fn.prettyTab = function(setting){
            var defauset = {
                current: 0,
                currentClass: 'on'
            };
            $.extend(defauset, setting);
            var current = defauset.current,
                curClass = defauset.currentClass;
            this.each(function(index, val) {
                var $this = $(this),
                    $nav = $this.find('.prettyTabNav'),
                    $con = $this.find(".prettyTabCont"),
                    $item = $this.find('.prettyTabItem');
                $nav.eq(current).addClass(curClass).siblings().removeClass(curClass);
                $item.hide().eq(current).show();
                $this.on('click','.prettyTabNav', function(event) {
                    var _this = $(this),
                        index = _this.index();
                    _this.addClass(curClass).siblings().removeClass(curClass);
                    $item.hide().eq(index).show();
                });
            });
        };
	}
};
BSTMG.tools = {
    //检测非空
    checkNull: function(para) {
        return para == null || para == '' ? '' : para;
    }
}
$(function() {
    BSTMG.common.init();
});